<?php
/**
 * 查询时间段配置
 */

// 读取 .env
function loadDotEnv(string $path): array {
    if (!is_file($path)) return [];
    $vars = [];
    foreach (file($path) as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') continue;
        $pos = strpos($line, '=');
        if ($pos === false) continue;
        $key = trim(substr($line, 0, $pos));
        $val = trim(substr($line, $pos + 1));
        if ((strlen($val) >= 2) && (($val[0] === '"' && substr($val, -1) === '"') || ($val[0] === "'" && substr($val, -1) === "'"))) {
            $val = substr($val, 1, -1);
        }
        $vars[$key] = $val;
    }
    return $vars;
}

$env = loadDotEnv(__DIR__ . '/.env');

$dbConfig = [
    'host' => $env['DB_MYSQL_HOST'] ?? getenv('DB_MYSQL_HOST') ?? '127.0.0.1',
    'port' => $env['DB_MYSQL_PORT'] ?? getenv('DB_MYSQL_PORT') ?? '3306',
    'database' => $env['DB_MYSQL_DATABASE'] ?? getenv('DB_MYSQL_DATABASE') ?? 'qiandao',
    'username' => $env['DB_MYSQL_USERNAME'] ?? getenv('DB_MYSQL_USERNAME') ?? 'root',
    'password' => $env['DB_MYSQL_PASSWORD'] ?? getenv('DB_MYSQL_PASSWORD') ?? '',
];

try {
    $dsn = "mysql:host={$dbConfig['host']};port={$dbConfig['port']};dbname={$dbConfig['database']};charset=utf8mb4";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    echo "=== 系统配置 ===\n\n";

    $stmt = $pdo->query("SELECT * FROM checkin_setting WHERE store_id = 0");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($config) {
        echo "单位分钟数: " . $config['unit_minutes'] . "\n";
        echo "单位积分: " . $config['unit_points'] . "\n";
        echo "时间段配置: " . $config['time_slots'] . "\n\n";

        $timeSlots = json_decode($config['time_slots'], true);
        if (is_array($timeSlots)) {
            echo "解析后的时间段:\n";
            foreach ($timeSlots as $slot) {
                echo "  - {$slot['start']} 到 {$slot['end']}: {$slot['points_per_hour']} 分/单位\n";
            }
        }
    } else {
        echo "未找到配置\n";
    }

    echo "\n=== 查询签到记录 ===\n\n";
    $stmt = $pdo->query("SELECT id, member_id, start_time, end_time, duration_minutes, points, create_time FROM checkin_record WHERE start_time = '2025-11-18 06:50:55' LIMIT 1");
    $record = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($record) {
        echo "记录ID: " . $record['id'] . "\n";
        echo "会员ID: " . $record['member_id'] . "\n";
        echo "开始时间: " . $record['start_time'] . "\n";
        echo "结束时间: " . $record['end_time'] . "\n";
        echo "时长: " . $record['duration_minutes'] . " 分钟\n";
        echo "积分: " . $record['points'] . " 分\n";
        echo "创建时间: " . $record['create_time'] . "\n";
    } else {
        echo "未找到记录\n";
    }

} catch (PDOException $e) {
    echo "数据库错误: " . $e->getMessage() . "\n";
}

